<template>
  <el-tabs
    v-model="activeTab"
    class="demo-tabs"
    @tab-click="handleClick"
    v-if="exptForm.campList.length"
  >
    <el-tab-pane
      :label="item.name"
      :name="item.id"
      v-for="item in exptForm.campList"
    >
    </el-tab-pane>
  </el-tabs>

  <div class="entity-container" v-if="exptForm.campList.length">
    <div class="jt" @click="addEntity">></div>
    <div class="entity-left">
      <div class="entity-tabs">
        <div
          v-for="(item, index) in entityTabs"
          :key="index"
          class="tab"
          :class="{ 'active-tab': activeEntity == index }"
          @click="entityClick(item, index)"
        >
          {{ item.name }}
        </div>
      </div>

      <div class="search">
        <el-input
          v-model="entityName"
          placeholder="请输入实体名称"
          size="small"
        >
          <template #prefix>
            <el-icon class="el-input__icon">
              <search />
            </el-icon>
          </template>
        </el-input>
        <el-button @click="searchEntity">搜索</el-button>
      </div>

      <el-tree
        v-if="activeEntity == 0"
        :current-node-key="currentEntityId"
        :data="entityList"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        ref="entityRef"
      >
        <template #default="{ node, data }">
          <span :id="data.id">{{ node.label }}</span>
        </template>
      </el-tree>
      <el-tree
        v-if="activeEntity == 1"
        :current-node-key="currentEntityId"
        :data="formationList"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        ref="formationRef"
      >
        <template #default="{ node, data }">
          <span :id="data.id">{{ node.label }}</span>
        </template>
      </el-tree>
    </div>
    <div class="entity-right">
      <div class="title">已选兵力</div>
      <div class="search">
        <el-input
          v-model="selectedEntityName"
          placeholder="请输入实体名称"
          size="small"
        >
          <template #prefix>
            <el-icon class="el-input__icon">
              <search />
            </el-icon>
          </template>
        </el-input>
        <el-button @click="selectedSearchEntity">搜索</el-button>
      </div>
      <el-tree
        :current-node-key="selectedCurrentEntityId"
        v-if="activeEntity == 0 && exptForm.campList.length"
        :data="exptForm.campList[currentIndex].entityList"
        :props="defaultProps"
        node-key="id"
        :default-expand-all="true"
        ref="selectedEntityRef"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span :id="data.id">{{ data.name }}</span>
            <span class="r">
              <el-input-number
                v-model="data.num"
                size="small"
                v-if="!data.children"
              ></el-input-number>
              <a
                style="margin-left: 8px"
                @click.stop="entityremove(node, data)"
              >
                删除
              </a>
            </span>
          </span>
        </template>
      </el-tree>

      <el-tree
        :current-node-key="selectedCurrentEntityId"
        v-if="activeEntity == 1"
        :data="exptForm.campList[currentIndex].formationList"
        :props="defaultProps"
        node-key="id"
        :default-expand-all="true"
        ref="selectedFormationRef"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span :id="data.id">{{ data.name }}</span>
            <span class="r">
            C
              <a
                style="margin-left: 8px"
                @click.stop="formationRemove(node, data)"
              >
                删除
              </a>
            </span>
          </span>
        </template>
      </el-tree>
    </div>
  </div>
  <div v-else class="tip">请先回到上一步，进行阵营设置</div>
  <el-form-item label="实验兵力描述" prop="troopsDescribe">
    <el-input v-model="exptForm.troopsDescribe" type="textarea" :rows="5" />
  </el-form-item>
</template>
<script setup>
import { ref, onMounted, onUnmounted, inject, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
const props = defineProps({
  exptForm: {
    type: Object,
    default: () => {
      return {};
    },
  },
});
let emit = defineEmits([""]);

const handleClick = (tab, event) => {
  console.log(tab.props.name);
  console.log(tab);
  activeTab.value = tab.props.name;
  currentIndex.value = findindex(props.exptForm.campList, activeTab.value);
};
// 阵营
// const activeTab = props.exptForm.campList[0]
//   ? ref(props.exptForm.campList[0].id)
//   : ref('');
const activeTab = ref("");

function findindex(arr, id) {
  let index = arr.findIndex((v) => v.id == id);
  console.log(index);
  if (index != -1) {
    return index;
  }
}

let currentIndex = ref("");

watch(
  () => props.exptForm.campList,
  (val, preVal) => {
    //val为修改后的值,preVal为修改前的值
    if (val && val.length) {
      if (activeTab.value == "") {
        activeTab.value = val[0].id;
        currentIndex.value = findindex(val, activeTab.value);
      }
    }
  },
  {
    //如果加了这个参数，值为true的话，就消除了惰性，watch会在创建后立即执行一次
    //那么首次执行，val为默认值,preVal为undefined
    immediate: true,
    //这个参数代表监听对象时，可以监听深度嵌套的对象属性
    //比如message是一个对象的话，可以监听到message.a.b.c，也就是message下的所有属性
    deep: true,
  }
);

// 实体单元切换
const entityTabs = [
  {
    name: "实体单元",
    id: 0,
  },
  {
    name: "编成编制",
    id: 1,
  },
];

const activeEntity = ref(0);
const entityClick = (item, index) => {
  activeEntity.value = index;
  entityName.value = "";
  selectedEntityName.value = "";
};

const defaultProps = {
  label: "name",
  children: "children",
};
const entityRef = ref(null);
// 实体单元列表
const currentId = ref("");
const entityList = ref([
  {
    name: "卫星",
    id: 1,
    children: [
      {
        name: "电子侦察卫星",
        id: 11,
        pid: 1,
      },
      {
        name: "图像侦察卫星",
        id: 12,
        pid: 1,
      },
      {
        name: "通信卫星",
        id: 13,
        pid: 1,
      },
      {
        name: "导航卫星",
        id: 14,
        pid: 1,
      },
      {
        name: "测绘卫星",
        id: 15,
        pid: 1,
      },
      {
        name: "电子对抗卫星",
        id: 16,
        pid: 1,
      },
    ],
  },
  {
    name: "导弹车",
    id: 2,
    children: [
      {
        name: "导弹车1",
        id: 21,
        pid: 2,
      },
      {
        name: "导弹车2",
        id: 22,
        pid: 2,
      },
    ],
  },
  {
    name: "飞机",
    id: 3,
    children: [
      {
        name: "飞机1",
        pid: 3,
        id: 31,
      },
      {
        name: "飞机2",
        id: 32,
        pid: 3,
      },
    ],
  },
]);
const selectedEntityList = ref([]);
const selectedEntityRef = ref(null);

// 编成编制列表
const formationList = ref([
  {
    name: "东部战区",
    id: 1,
    children: [
      {
        name: "东海舰队",
        id: 11,
      },
      {
        name: "空军",
        id: 12,
      },
      {
        name: "火箭军",
        id: 13,
      },
      {
        name: "陆军",
        id: 14,
      },
      {
        name: "坦克军",
        id: 15,
        children: [
          {
            name: "坦克师",
            id: 151,
            children: [
              {
                name: "xx坦克1",
                id: 1511,
              },
              {
                name: "xx坦克2",
                id: 1512,
              },
            ],
          },
        ],
      },
    ],
  },
  {
    name: "南部战区",
    id: 2,
    children: [
      {
        name: "空军",
        id: 21,
      },
      {
        name: "陆军",
        id: 22,
      },
    ],
  },
]);
const formationRef = ref(null);
const selectedFormationList = ref(null);
const selectedFormationRef = ref(null);

// 搜索实体

function tree(data, name) {
  for (let i = 0; i < data.length; i++) {
    let item = data[i];

    if (item.name == name) {
      return item;
    } else {
      // item.children 不等于 undefined && item.children.length 大于 0 时
      if (item.children && item.children.length > 0) {
        let res = tree(item.children, name);

        // 当 res = undefined 时不会进入判断中
        // 也就是不会return
        if (res) return res;
      }
    }
  }
}
const entityName = ref("");
const currentEntityId = ref("");
const searchEntity = () => {
  if (activeEntity.value == 0) {
    let t = tree(entityList.value, entityName.value);
    if (t) {
      currentEntityId.value = t.id;
      let node = document.getElementById(t.id);
      node.scrollIntoView();
    } else {
      ElMessage({
        showClose: true,
        message: "请输入正确的任务名称",
        type: "error",
      });
    }
  } else {
    let t = tree(formationList.value, entityName.value);
    if (t) {
      currentEntityId.value = t.id;
      let node = document.getElementById(t.id);
      node.scrollIntoView();
    } else {
      ElMessage({
        showClose: true,
        message: "请输入正确的任务名称",
        type: "error",
      });
    }
  }
};
// 搜索已选实体
const selectedEntityName = ref("");
const selectedCurrentEntityId = ref("");
const selectedSearchEntity = () => {
  if (activeEntity.value == 0) {
    let t = tree(selectedEntityList.value, selectedEntityName.value);
    if (t) {
      selectedCurrentEntityId.value = t.id;
      let node = document.getElementById(t.id);
      node.scrollIntoView();
    } else {
      ElMessage({
        showClose: true,
        message: "请输入正确的任务名称",
        type: "error",
      });
    }
  } else {
    let t = tree(selectedFormationList.value, selectedEntityName.value);
    if (t) {
      selectedCurrentEntityId.value = t.id;
      let node = document.getElementById(t.id);
      node.scrollIntoView();
    } else {
      ElMessage({
        showClose: true,
        message: "请输入正确的任务名称",
        type: "error",
      });
    }
  }
};
function treeFilter(tree, func) {
  return tree
    .map((node) => ({ ...node }))
    .filter((node) => {
      node.children = node.children && treeFilter(node.children, func);
      return func(node) || (node.children && node.children.length);
    });
}
const addEntity = () => {
  if (activeEntity.value == 0) {
    let ids = entityRef.value.getCheckedKeys();
    // selectedEntityList.value = treeFilter(entityList.value, (node) =>
    //   ids.includes(node.id)
    // );
    console.log(props.exptForm.campList[currentIndex.value]);
    props.exptForm.campList[currentIndex.value].entityList = treeFilter(
      entityList.value,
      (node) => ids.includes(node.id)
    );
  } else {
    let ids = formationRef.value.getCheckedKeys();
    // selectedFormationList.value = treeFilter(formationList.value, (node) =>
    //   ids.includes(node.id)
    // );
    props.exptForm.campList[currentIndex.value].formationList = treeFilter(
      formationList.value,
      (node) => ids.includes(node.id)
    );
  }
};
// 删除实体
const entityremove = (node, data) => {
  const parent = node.parent;
  const children = parent.data.children || parent.data;
  const index = children.findIndex((d) => d.id === data.id);
  children.splice(index, 1);

  //   selectedEntityList.value = [...selectedEntityList.value];
  console.log(props.exptForm.campList[currentIndex.value].entityList);
};
// 删除编制
const formationRemove = (node, data) => {
  const parent = node.parent;
  const children = parent.data.children || parent.data;
  const index = children.findIndex((d) => d.id === data.id);
  children.splice(index, 1);
  //   selectedFormationList.value = [...selectedFormationList.value];
};
onMounted(() => {});
</script>
<style scoped lang="scss">
.tip {
  text-align: center;

  line-height: 500px;
  width: 100% !important;
  margin: 0;
}
.entity-container {
  margin: 0 auto;
  width: 80%;
  height: calc(100% - 50px - 140px);
  // border: 1px solid red;
  margin-bottom: 10px;
  display: flex;
  position: relative;
  .jt {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 50px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    background: #14384e;
    border: 1px solid #5099a7;
    margin: 10px 0;
    z-index: 100;
  }
  .entity-left,
  .entity-right {
    flex: 1;
    border: 1px solid #797979;
    .search {
      margin-top: 10px;
      height: 30px;

      .el-input {
        width: 140px;
        margin-left: 10px;
      }

      :deep() {
        .el-input__wrapper {
          background: #051113 !important;
          border: 1px solid #007897;
          border-radius: 0 !important;
          box-shadow: none;
          box-sizing: border-box;

          height: 24px;

          .el-input__inner {
            color: #fff;
          }

          .el-icon {
            color: #fff;
          }
        }

        .el-button {
          border-radius: 0 !important;
          background: #007897;
          border: none;
          color: #fff;

          height: 24px;
        }
      }
    }
  }
  .entity-right {
    .title {
      background: #32697b;
      height: 30px;
      line-height: 30px;
      text-align: center;
    }
  }
  .entity-left {
    .entity-tabs {
      display: flex;
      .tab {
        flex: 1;
        background: #565656;
        height: 30px;
        line-height: 30px;
        text-align: center;
        margin: 0 1px;
      }
      .active-tab {
        background: #3088bf;
      }
    }
  }
}
:deep() {
  .el-form-item__label {
    color: #fff;
  }
  // tabs
  .el-tabs {
    width: 100%;
    height: 50px;

    overflow: hidden;
  }
  .el-tabs__item {
    color: #fff;
  }
  .is-active {
    color: red;
  }
  .el-tree {
    background: transparent;
    width: 100%;
    height: calc(100% - 90px);
    overflow-y: auto;
    margin-top: 10px;
    color: #fff;
    // background:red;

    .custom-tree-node {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
      .r {
        text-align: right;
        display: inline-block;
        width: 200px;
        float: right;
      }
    }
  }

  // el-tree-node is-expanded is-current is-focusable
  .el-tree-node.is-current > .el-tree-node__content {
    background-color: #2c4c60 !important;
  }

  .el-tree-node:focus > .el-tree-node__content {
    background-color: transparent;
  }

  .el-tree-node__content {
    &:hover {
      background-color: #2c4c60;
    }
  }

  .el-tree-node__content {
    background: transparent;
  }
}
</style>
